import os
from dotenv import load_dotenv
from sqlalchemy.orm import Session
from ..models.images_model import Images
from fastapi import HTTPException

load_dotenv()
SOURCES_PATH=os.getenv("SOURCES_PATH")
def get_image_by_id(db: Session, image_id: int):
    db_image = db.query(Images).filter(Images.id == image_id).first()
    if db_image :
        return db_image.as_dict()
    return HTTPException(status_code=404, detail="图片不存在")


def get_images(db: Session, skip: int = 0, limit: int = 100, to_dict=True):
    results = db.query(Images).offset(skip).limit(limit).all()
    if to_dict:
        return [img.as_dict() for img in results]
    return results


def create_image(db: Session, name: str, path: str, type: int = 1):
    # 检查是否存在同名图片
    existing = db.query(Images).filter(Images.name == name).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"图片名称 '{name}' 已存在")
    file_path=os.path.join(SOURCES_PATH, path)

    db_image = Images(name=name, path=path, type=type,
                      oss_url="http://whatteam1.oss-cn-beijing.aliyuncs.com/"+path)
    db.add(db_image)
    db.commit()
    db.refresh(db_image)
    return db_image.as_dict()




def update_image(db: Session, image_id: int, data: dict):
    db_image = db.query(Images).filter(Images.id == image_id).first()
    if not db_image:
        return None

    for key, value in data.items():
        setattr(db_image, key, value)

    db.commit()
    db.refresh(db_image)
    return db_image.as_dict()


def delete_image(db: Session, image_id: int):
    db_image = db.query(Images).filter(Images.id == image_id).first()
    if db_image:
        db.delete(db_image)
        db.commit()
        return db_image.as_dict()
    raise HTTPException(status_code=404, detail="图片不存在")



# if __name__ == "__main__":
#     from database.db import SessionLocal
#     db = SessionLocal()

